package com.msh.frame.common.util;

import com.msh.frame.common.util.AesUtil.AesInstance;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import lombok.SneakyThrows;

/**
 * 多线程测试类
 */
public class MultiThreadTestUtil {

  private static final int ONT_THREAD_NUM = 100000;
  private static final int THREAD_COUNT = 100;
  private static long start = 0;

  /**
   * 例子
   */
  public static void main(String[] args) throws InterruptedException {
    AesInstance instance = AesUtil.getInstance("1234567890123456");
    MultiThreadTestUtil.threadTest(instance, (d) -> {
      String str = String.valueOf(new Random().nextDouble());
      String encrypt = d.encrypt(str);
      String decrypt = d.decrypt(encrypt);
      System.out.println(str.equals(decrypt));
    });
  }

  /**
   * 启动线程测试
   */
  public static <T> void threadTest(T t, IWork<T> work) throws InterruptedException {
    ThreadInstance[] ts = new ThreadInstance[THREAD_COUNT];
    for (int i = 0; i < THREAD_COUNT; i++) {
      ts[i] = new ThreadInstance(t, work);
    }

    start = System.currentTimeMillis();
    for (int i = 0; i < THREAD_COUNT; i++) {
      ts[i].start();
    }
    while (true) {
      TimeUnit.SECONDS.sleep(3000);
    }
  }


  public static class ThreadInstance<T> extends Thread {

    private T t;
    private IWork<T> work;

    public ThreadInstance(T t, IWork<T> work) {
      this.t = t;
      this.work = work;
    }

    @SneakyThrows
    @Override
    public void run() {
      int i = 0;
      while (i++ < ONT_THREAD_NUM) {
        work.doWork(t);
      }
      System.out
          .println(this.getName() + " is end. time user :" + (System.currentTimeMillis() - start));
    }
  }

  public static interface IWork<T> {

    void doWork(T t) throws Exception;
  }
}
